package com.glsc.ngateway.opmanage.service;

import com.glsc.ngateway.common.base.domain.mysql.gateway.platform.Dict;
import com.glsc.ngateway.common.base.domain.mysql.gateway.platform.MysqlDataDictionary;
import com.glsc.ngateway.opmanage.exception.PlatformException;
import com.glsc.ngateway.common.base.repo.mysql.gateway.platform.DictRepo;
import com.glsc.ngateway.common.base.repo.mysql.gateway.platform.MysqlDataDictionaryRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.TreeSet;

/**
 * 功能描述: <br>
 *
 * @author gaojc
 * @date 2020/9/8 17:20
 */
@Service
public class DictService {

    private DictRepo dictRepo;
    private MysqlDataDictionaryRepository mysqlDataDictionaryRepository;

    @Autowired
    public void setDictRepo(DictRepo dictRepo) {
        this.dictRepo = dictRepo;
    }

    @Autowired
    public void setMysqlDataDictionaryRepository(MysqlDataDictionaryRepository mysqlDataDictionaryRepository) {
        this.mysqlDataDictionaryRepository = mysqlDataDictionaryRepository;
    }


    public Dict findByCode(String dictField, String dictSpace) {
        Dict dict = dictRepo.queryByDictCode(dictField, dictSpace);
        TreeSet dictValues = new TreeSet(Comparator.comparing((MysqlDataDictionary e) -> Integer.parseInt(e.getfOrder())));
        dictValues.addAll(dict.getDictValues());
        dict.setDictValues(dictValues);
        return dict;
    }

    public Dict findById(long dictMapId) {
        Dict dict = null;
        /*dict = cacheUtils.getDictCache().getById(dictMapId);
        if(dict == null) {
            dict = new DictDto(dictRepo.findById(dictMapId));
        }*/
        dict = dictRepo.findById(dictMapId);
        TreeSet dictValues = new TreeSet(Comparator.comparing((MysqlDataDictionary e) -> Integer.parseInt(e.getfOrder())));
        dictValues.addAll(dict.getDictValues());
        dict.setDictValues(dictValues);
        return dict;
    }

    public Page<Dict> findPage(Specification s, int page, int size) {
        Sort sort = Sort.by("tableName", "fieldName");
        Pageable pageable = PageRequest.of(page - 1, size, sort);
        return dictRepo.findAll(s, pageable);
    }

    @Transactional
    public Dict add(Dict dict) {
        if (dict.getDictMapId() != null) {
            throw PlatformException.error("新增字典不要输入id", true, false);
        }

        String tableName = dict.getTableName();
        String fieldName = dict.getDictField();
        String dictSpace = dict.getDictSpace();
        if (dictRepo.queryByFieldName(fieldName, tableName) != null) {
            throw PlatformException.error("字典项代码已存在，不能重复", true, false);
        }
        if (dict.getDictValues() != null) {
            dict.getDictValues().forEach(value -> {
                value.setFieldName(fieldName);
                value.setDictSpace(dictSpace);
                value.setfStatus("1");
            });
            mysqlDataDictionaryRepository.saveAll(dict.getDictValues());
        }
        return dictRepo.save(dict);
    }

    @Transactional
    public Dict addFundDict(Dict dict) {
        if (dict.getDictMapId() != null) {
            throw PlatformException.error("新增字典不要输入id", true, false);
        }
        dict.setfType("VARCHAR");
        dict.setTableName("ALL_TABLE");
        dict.setFieldName(dict.getDictField());
        dict.setDictSpace("GLOBAL");
        String tableName = dict.getTableName();
        String fieldName = dict.getDictField();
        String dictSpace = dict.getDictSpace();
        if (dictRepo.queryByFieldName(fieldName, tableName) != null) {
            throw PlatformException.error("字典项代码已存在，不能重复", true, false);
        }
        if (dict.getDictValues() != null) {
            dict.getDictValues().forEach(value -> {
                value.setFieldName(fieldName);
                value.setDictSpace(dictSpace);
                value.setfStatus("1");
            });
            mysqlDataDictionaryRepository.saveAll(dict.getDictValues());
        }
        return dictRepo.save(dict);
    }

    @Transactional
    public void addFundDictDate(MysqlDataDictionary mysqlDataDictionary) {
        int i = mysqlDataDictionaryRepository.findMaxOrder("PLACE", "GLOBAL");
        i = i + 1;
        mysqlDataDictionary.setfStatus("1");
        mysqlDataDictionary.setFieldName("PLACE");
        mysqlDataDictionary.setDictSpace("GLOBAL");
        mysqlDataDictionary.setfOrder(String.valueOf(i));
        mysqlDataDictionaryRepository.save(mysqlDataDictionary);
    }

    @Transactional
    public Dict update(Dict dict) {
        if (dict.getDictMapId() == null) {
            throw PlatformException.error("更新字典信息必须输入id", true, false);
        }
        String tableName = dict.getTableName();
        String fieldName = dict.getDictField();
        String dictSpace = dict.getDictSpace();
        if (tableName == null || tableName.isEmpty() || fieldName == null || fieldName.isEmpty()) {
            throw PlatformException.error("字典项代码/名称不可以为空", true, false);
        }
        if (dict.getDictValues() != null) {
            List<Long> dicIds = new ArrayList<>();
            dict.getDictValues().forEach(value -> {
                dicIds.add(value.getDicId());
                value.setFieldName(fieldName);
                value.setDictSpace(dictSpace);
                value.setfStatus("1");
                mysqlDataDictionaryRepository.save(value);
            });
            if (dicIds.size() > 0) {
                mysqlDataDictionaryRepository.deleteById(dicIds, fieldName, dictSpace);
            }
        }
        return dictRepo.save(dict);
    }

    public int delete(long dictMapId) {
        Dict dict = dictRepo.findById(dictMapId);
        mysqlDataDictionaryRepository.deleteById(dict.getDictSpace(), dict.getDictField());
        return dictRepo.deleteById(dictMapId);
    }

}
